package cz.tpj.database;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Třída podle vzoru <i>singelton</i>. Pro získání instance této třídy se musí
 * zavolat metoda {@link #getInstance()}, pro pro získání připojení je metoda
 * {@link #getConnection()}.
 * @author Martin
 */
public class DatabaseConnector {
    private static DatabaseConnector im = null;
    private static String connectString = "jdbc:mysql://localhost/mydb?" +
			                           "user=turista&password=ttt" +
                                       "&useUnicode=true&characterEncoding=UTF-8";
    private Connection con = null;
    //================================soukromy konstruktor========================
    private DatabaseConnector(){
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
	} catch (Exception e) {
            e.printStackTrace();
	}
    }

    public static DatabaseConnector getInstance(){
        if(im == null){
            im = new DatabaseConnector();
        }
        return im;
    }

    public Connection getConnection(){
        if(con == null){
            try {
                con = DriverManager.getConnection(connectString);
                con.setAutoCommit(false);
            } catch (SQLException ex) {
                Logger.getLogger(DatabaseConnector.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return con;
    }
}
